package com.rwy.web.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.rwy.dto.user.UserDTO;
import com.rwy.service.UserManageService;
import com.rwy.util.CollectionUtil;
import com.rwy.util.CommonController;
import com.rwy.util.MemberDTO;
import com.rwy.util.ObjectUtil;
import com.rwy.util.RWYException;
import com.rwy.util.StringUtil;
import com.rwy.util.constant.AppTokenEnum;
import com.rwy.util.constant.CacheKeyEnum;
import com.rwy.util.constant.CacheValueKeyEnum;
import com.rwy.web.filter.authorize.AuthorizeRespDTO;
import com.tool.http.httpclient.HttpClientUtil;
import com.tool.util.http.common.HttpConfig;

import lombok.extern.log4j.Log4j;

@RestController
@RequestMapping("/user")
@Log4j
public class UserCenterController extends CommonController {
	@Autowired
	UserManageService userService;
	
	//测试使用跳过权限校验
	@RequestMapping("/authorize")
	public ModelAndView testGetUser() {
		ModelAndView mv = new ModelAndView();//18126835836
		UserDTO businessUser = userService.getBusinessPartnerByMObile("18819300173");
		addUserCacheElement("chenj", businessUser);
		mv.addObject(AppTokenEnum.common_app_token.getToken_key(), "chenj");
		mv.addObject("api_domain", api_domain);
		mv.setViewName("index");
		return mv;
	}
	
	
	//正式 获取用户授权码 ,提供回调
	//@RequestMapping("/authorize")
	public ModelAndView userAuthorize(HttpServletRequest request, String code) throws Exception {
		ModelAndView mv = new ModelAndView();
		String erroMsg = "";
		AuthorizeRespDTO tokenDto = null;
		try {
			// 获取员工code, 然后
			if (StringUtil.isEmpty(code)) {
				log.error("get user code fail ..!");
				erroMsg = "用户授权失败请重新请求!";
				throw RWYException.create(HttpStatus.SC_UNAUTHORIZED);
			}
			
			tokenDto = getCommonAccessToken();
			if (ObjectUtil.isEmpty(tokenDto)) {
				erroMsg = "用户授权失败请重新请求!";
				throw RWYException.create(HttpStatus.SC_UNAUTHORIZED);
			}
			// 获取成员信息
			String userInfo = HttpClientUtil.get(HttpConfig.custom().url(login_get_user_info + "?access_token=" + tokenDto.getAccess_token() + "&code=" + code));
			AuthorizeRespDTO user = JSON.parseObject(userInfo, AuthorizeRespDTO.class);
			if (ObjectUtil.isEmpty(user) || StringUtil.isEmpty(user.getUserId())) {
				log.error("get user info userid fail ..." + userInfo);
				erroMsg = "你没有该应用访问权限,请联系管理员!";
				throw RWYException.create(HttpStatus.SC_UNAUTHORIZED);
			}
			// 获取openID
			/*String body = "{\"userid\":\""+user.getUserId()+"\"}";
			String openIdObj = HttpClientUtil.post(HttpConfig.custom().url("http://qydev.weixin.qq.com/cgi-bin/apiagent?tid=73&access_token="+tokenDto.getAccess_token()+"&body=" + URLEncoder.encode(body) + "&f=json"));
			//String openIdObj = HttpClientUtil.post(HttpConfig.custom().url(login_get_openId_by_userId+"?tid=73&access_token="+tokenDto.getAccess_token()+"&body="+ URLEncoder.encode(body)+"&f=json"));
			//uthorizeRespDTO wxOpen = JSON.parseObject(openIdObj, AuthorizeRespDTO.class);
			
			if (ObjectUtil.isEmpty(openIdObj) || openIdObj.indexOf("openid") <1) {
				log.error("get openid fail ... !" + openIdObj);
				throw RWYException.create(HttpStatus.SC_UNAUTHORIZED);
			}
			String openid = "";
			if(openIdObj.indexOf("openid") > 0) {
				String tt = openIdObj.substring(openIdObj.indexOf("openid"));
				openid = tt.substring(11, tt.indexOf("\\\"}"));
				log.info("openid:" + openid);
			}
            if(StringUtil.isEmpty(openid)) {
            	log.error("get openid fail ... !" + openIdObj);
				throw RWYException.create(HttpStatus.SC_UNAUTHORIZED);
            }*/
			//获取员工信息
			String mes = HttpClientUtil.get(HttpConfig.custom().url(get_member_mesage_url+"?access_token="+tokenDto.getAccess_token()+"&userid="+user.getUserId()));
			MemberDTO member = JSON.parseObject(mes, MemberDTO.class);
			if(StringUtil.isEmpty(mes)|| ObjectUtil.isEmpty(member) ||StringUtil.isEmpty(member.getMobile())){
				log.error("get member message fail ... !" + mes);
				erroMsg = "管理员没有授权用户手机号, 请联系管理员!";
				throw RWYException.create(101);
			}
			
 			UserDTO businessUser = userService.getBusinessPartnerByMObile(member.getMobile());
			if (ObjectUtil.isEmpty(businessUser) || null == businessUser.getBusinessPartnerID() || CollectionUtil.isEmpty(businessUser.getPartnerIds())) {
				log.error("user unAuthorize not has businessPartner role !");
				erroMsg = "您没有权限访问商家数据,请向管理员申请商家权限!";
				throw RWYException.create(101);
			} else {
				String key = StringUtil.getUUID();
				addUserCacheElement(key, businessUser);
				mv.addObject(AppTokenEnum.common_app_token.getToken_key(), key);
				mv.setViewName("index");
			}
		} catch (Exception e) {
			mv.setViewName("auto");
			log.error(e.getMessage());
			if (e instanceof RWYException) {
				  mv.addObject("msg", erroMsg);
			}else {
				mv.addObject("msg", "出错了,请重新请求或联系管理员!");
				//throw e;
			}
		}
		return mv;
	}
	
	
}
